package m4_routing;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

public class Consumer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("192.168.126.130");
        cf.setUsername("admin");
        cf.setPassword("admin");
        Channel c = cf.newConnection().createChannel();

        //定义交换机，定义随机队列，绑定
        c.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);
        String queue = UUID.randomUUID().toString();
        c.queueDeclare(queue, false, true, true, null);
        System.out.println("输入绑定键，用空格隔开：");
        String s = new Scanner(System.in).nextLine();
        String[] keys = s.split("\\s+");
        for (String key : keys) {
            c.queueBind(queue, "direct_logs", key);
        }
        DeliverCallback deliverCallback = new DeliverCallback() {

            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody(),"UTF-8");
                String key = message.getEnvelope().getRoutingKey();
                System.out.println(key + " - " + msg);
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {

            @Override
            public void handle(String consumerTag) throws IOException {

            }
        };
        //从随机队列接收数据
        c.basicConsume(queue, true, deliverCallback, cancelCallback);
    }
}
